package com.lianqi.emcpframework.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @program emcp-framework
 * @ClassName PinyinUtils
 * @description: 汉语拼音工具类
 * @author: sky
 * @create: 2018/11/13 13:39
 */
public class PinyinUtils {

    /**
     * 字符串转换为拼音
     * 
     * @param str
     * @return
     */
    public static String toPingYin(String str) {
        char[] chars = str.toCharArray();
        HanyuPinyinOutputFormat pinyinFormat = initPinYinFormat();
        String pinyinStr = "";
        try {
            for (int i = 0; i < chars.length; i++) {
                pinyinStr += warpPinyin(chars[i], pinyinFormat);
            }
            return pinyinStr;
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return pinyinStr;
    }

    private static HanyuPinyinOutputFormat initPinYinFormat() {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        // 不使用音标
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        // u转为v
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        return format;
    }

    private static String warpPinyin(char aChar, HanyuPinyinOutputFormat format)
        throws BadHanyuPinyinOutputFormatCombination {
        String str = "";
        String[] pinyin;
        if (StringUtils.containsChineseChar(Character.toString(aChar))) {
            pinyin = PinyinHelper.toHanyuPinyinStringArray(aChar, format);
            // 多音字默认取第一个
            str += pinyin[0];
        } else {
            str += Character.toString(aChar);
        }
        return str;
    }

    /**
     * 获取中文字符串首字母
     * 
     * @param str
     *            中文字符串
     * @return String
     */
    public static String toShotHandPinyin(String str) {
        String convert = "";
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyin != null) {
                if (!"none0".equals(pinyin[0])) {
                    convert += pinyin[0].charAt(0);
                }
            } else {
                convert += word;
            }
        }
        return convert;
    }

}
